package com.hefan.api.controller.pub;

import java.math.BigDecimal;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.cat.common.meta.PaymentTypeEnum;
import com.cat.tiger.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.ctc.wstx.util.StringUtil;
import com.google.common.collect.Maps;
import com.hefan.api.service.CurrencyRechargeLocalService;
import com.hefan.api.service.UserLocalService;
import com.hefan.api.service.pay.PayLocalService;
import com.hefan.common.util.HttpUtils;
import com.hefan.common.util.MapUtils;
import com.hefan.pay.bean.PayExtendVo;
import com.hefan.pay.bean.TradeLog;
import com.hefan.user.bean.WebUser;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/pub")
public class PayOrderForPcController {

	private Logger logger = LoggerFactory.getLogger(PayOrderForPcController.class);
	@Resource
	private PayLocalService payLocalService;

	@Resource
	private UserLocalService userLocalService;

	@Resource
	private CurrencyRechargeLocalService currencyRechargeLocalService;

	@RequestMapping("/pcPayOrder")
	@ResponseBody
	public String pcPayOrder(HttpServletRequest req) {
		ResultBean result = new ResultBean(ResultCode.SUCCESS, null);
		try {
			Map map = HttpUtils.initParam(req, Map.class);
			if (CollectionUtils.isEmpty(map) || !map.containsKey("userId") || !map.containsKey("paymentType")
					|| !map.containsKey("id")) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			String userId = String.valueOf(map.get("userId"));
			int paymentType = Integer.valueOf(String.valueOf(map.get("paymentType")));
			PaymentTypeEnum paymentTypeEnum = PaymentTypeEnum.getPaymentTypeEnumByPaymentType(paymentType);
			if (org.apache.commons.lang.StringUtils.isBlank(userId) || paymentTypeEnum == null) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			int exchangeRechargeId = Integer.valueOf(String.valueOf(map.get("id")));
			// 如果是ios支付 exchangeRechargeId 不能为 0
			if (exchangeRechargeId == 0
					&& paymentTypeEnum.getPaymentType() == paymentTypeEnum.IOS_APPLE_PAY.getPaymentType()) {
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			String fanpiao = "0";
			if (Integer.valueOf(String.valueOf(map.get("id"))) == 0) {
				if (!map.containsKey("fanpiao")
						|| org.apache.commons.lang.StringUtils.isBlank(String.valueOf(map.get("fanpiao")))) {
					return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
				}
				fanpiao = String.valueOf(map.get("fanpiao"));
			}
			TradeLog tradeLog = new TradeLog();
			tradeLog.setUserId(userId);
			tradeLog.setPaymentType(paymentType);
			tradeLog.setIncome(Integer.valueOf(fanpiao));
			PayExtendVo payExtendVo = new PayExtendVo();
			payExtendVo.setUserId(userId);
			if (map.containsKey("returnUrl")) {
				payExtendVo.setReturnUrl(String.valueOf(map.get("returnUrl")));
			}
			// 如果时pc 支付宝支付时需要设置自定义二维码宽度
			if (paymentTypeEnum.getPaymentType() == PaymentTypeEnum.PC_ALIPAY_PAY.getPaymentType()) {
				payExtendVo.setQrcodeWidth(StringUtils.isBlank(String.valueOf(map.get("qrcodeWidth"))) ? "30"
						: String.valueOf(map.get("qrcodeWidth")));
			}
			result = payLocalService.createOrder(paymentTypeEnum, tradeLog, payExtendVo, exchangeRechargeId, req);
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(new ResultBean(ResultCode.UnknownException, null));
		}

		return JSON.toJSONString(result);
	}

	/**
	 * web充值比例
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/rechargeForPc")
	@ResponseBody
	public String rechargeForPc(HttpServletRequest request) {
		ResultBean result = new ResultBean();
		Map mapUser = HttpUtils.initParam(request, Map.class);
		if(CollectionUtils.isEmpty(mapUser) || !mapUser.containsKey("type")) {
			return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
		}
		try {
			Map map = Maps.newHashMap();
			if(mapUser.containsKey("userId") && !StringUtils.isBlank(String.valueOf(mapUser.get("userId")))) {
				//存在用户id时需要返回用户基本信息
				String userId = mapUser.get("userId").toString();
				WebUser user = userLocalService.getWebUserByUserId(userId);
				if(user != null) {
					user.setPasswords(null);
					user.setMobile(null);
					user.setOpenidWx(null);
					user.setOpenidWb(null);
					user.setOpenidQq(null);
				}
				map.put("user", user);
			}
			int type = MapUtils.getIntValue(mapUser, "type", 0);
			PaymentTypeEnum paymentTypeEnum = PaymentTypeEnum.getPaymentTypeEnumByPaymentType(type);
			if(paymentTypeEnum == null) { //验证支付类型是否存在
				return JSON.toJSONString(new ResultBean(ResultCode.ParamException, null));
			}
			map.put("rechargeForPc", currencyRechargeLocalService.getCurrencyRecharge(paymentTypeEnum.getRechargeStatus(), null));
			map.put("exchange", currencyRechargeLocalService.getExchange(paymentTypeEnum.getExchangeRuleType(), null));
			result.setCode(ResultCode.SUCCESS.get_code());
			result.setData(map);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			result.setCode(ResultCode.UNSUCCESS.get_code());
		}
		return JSON.toJSONString(result);

	}

	/**
	 * 根据ID查询订单状态
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/getTradeLogByOrderId")
	@ResponseBody
	public String getTradeLogByOrderId(HttpServletRequest req) {
		ResultBean resultBean = new ResultBean();
		try {

			Map map = HttpUtils.initParam(req, Map.class);

			String orderId = String.valueOf(map.get("orderId"));
			if (payLocalService.checkOrderId(orderId)) {

				resultBean.setCode(ResultCode.SUCCESS.get_code());
				resultBean.setData(payLocalService.getTradeLogByOrderId(orderId));
			} else {

				resultBean.setCode(ResultCode.PayOrderError.get_code());
				resultBean.setMsg(ResultCode.PayOrderError.getMsg());
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			resultBean.setData(ResultCode.UnknownException);
			resultBean.setData(e.getMessage());
		}
		return JSON.toJSONString(resultBean);
	}
}
